package com.linovi.map

class Map {

  val size: Int = 4096
  var list = new Array[Entry](size)

  def get(k: String): String = {
    var hashOfKey: Int = k.hashCode().abs % size
    var entry: Entry = list(hashOfKey)
    var isFound: Boolean = false

    while (!isFound && entry != null) {
      if (entry.key == k) {
        isFound = true
      } else {
        entry = entry.next
      }
    }
    if (entry != null) {
      entry.value
    } else {
      null
    }
  }

  def put(k: String, v: String): Unit = {
    var hashOfKey: Int = k.hashCode().abs % size
    var entry: Entry = list(hashOfKey)

    if (entry == null) {
      list(hashOfKey) = new Entry(k, v)
    } else {
      while (entry.key != k && entry.next != null) {
        entry = entry.next
      }
      if (entry.next != null) {
        entry.value = v
      } else {
        var newEntry: Entry = new Entry(k, v)
        newEntry.previous = entry
        entry.next = newEntry
      }
    }
  }

  def remove(k: String): Boolean = {
    var hashOfKey: Int = k.hashCode().abs % size
    var entry: Entry = list(hashOfKey)
    var isRemoved: Boolean = false

  /*  while (entry != null) {
      if (k != entry.key) {
        entry = entry.next
      } else if (entry.next != null) {
        entry.next = entry

      }
    }*/

    while (entry != null) {
      if (k != entry.key) {
        entry = entry.next
      } else if (entry.previous == null && entry.next != null) {
        val newHead = entry.next
        newHead.previous = null
        list(hashOfKey) = newHead
      } else if (entry.next == null && entry.previous != null) {
        entry.previous.next = null
        entry.previous = null
      } else if (entry.next == null && entry.previous == null) {
        entry = null
      } else if (entry.next != null && entry.previous != null) {
        entry.previous.next = entry.next
        entry.next.previous = entry.previous
      }
      isRemoved = true
    }
    isRemoved
  }
}

  